<template>
  <div class="add-topic">
    <a-modal
      class="loading"
      :visible="visible"
      width="50%"
      :title="title"
      @cancel="handleClose"
      @ok="handleOk"
    >
      <a-form class="form" :model="addSubjectForm" name="basic" ref="formRef" :rules="rules">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="科目代码" name="kmdm">
              <a-input v-model:value="addSubjectForm.kmdm" placeholder="请输入科目代码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="科目名称" name="kmmc">
              <a-input v-model:value="addSubjectForm.kmmc" placeholder="请输入科目名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="kmzfs">
              <template #label>
                <span>
                  <span style="color: red">*</span>
                  <span style="margin-left: 5px">科目分数</span>
                </span>
              </template>
              <a-input v-model:value="addSubjectForm.kmzfs" placeholder="请输入科目分数" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属学院" name="xyxxId">
              <a-select
                allowClear
                :disabled="userInfo.accountType == 'XY'"
                v-model:value="addSubjectForm.xyxxId"
                :field-names="{ label: 'codeName', value: 'id' }"
                :options="collegeList"
                placeholder="请选择学院"
                show-search
                :filter-option="selectFilterOption"
              >
                <template #suffixIcon>
                  <caret-down-outlined class="ant-select-suffix" />
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="评阅组长" name="kmzz">
              <a-select
                v-model:value="addSubjectForm.kmzz"
                show-search
                allowClear
                :default-active-first-option="false"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                :options="teacherOptions"
                @search="handleChange"
                :field-names="{ label: 'jsxm', value: 'userId' }"
                placeholder="请选择质检教师（可按工号或姓名搜索）"
              >
                <template #suffixIcon>
                  <caret-down-outlined class="ant-select-suffix" />
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col
            :span="12"
            v-if="userInfo.accountType == 'ADMIN' || userInfo.accountType == 'ADMIN'"
          >
            <a-form-item label="质检教师" name="zjlsIds">
              <a-select
                v-model:value="addSubjectForm.zjlsIds"
                show-search
                allowClear
                mode="multiple"
                :default-active-first-option="false"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                :options="teacherOptions"
                @search="handleChange"
                :field-names="{ label: 'jsxm', value: 'userId' }"
                placeholder="请选择质检教师（可按工号或姓名搜索）"
              >
                <template #suffixIcon>
                  <caret-down-outlined class="ant-select-suffix" />
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="16">
            <a-form-item label="考试开始时间" name="timeArr">
              <a-range-picker
                :format="'YYYY-MM-DD HH:mm:ss'"
                v-model:value="addSubjectForm.timeArr"
                show-time
              />
            </a-form-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-item label="应到份数" name="ydsjFs">
              <!-- defaultValue="5" -->
              <a-input-number disabled v-model:value="addSubjectForm.ydsjFs" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="实到份数">
              <!-- defaultValue="5" -->
              <a-input-number disabled v-model:value="addSubjectForm.sjSjFs" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="缺考份数">
              <!-- defaultValue="5" -->
              <a-input-number disabled v-model:value="addSubjectForm.qkSjFs" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="试评试卷份数" name="spsjfs">
              <!-- defaultValue="5" -->
              <a-input-number
                :disabled="addSubjectForm.kmPyzt == 'FORMAL' || addSubjectForm.kmPyzt == 'TEST'"
                v-model:value="addSubjectForm.spsjfs"
                :min="0"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="质检比率（%）" name="zjbl">
              <!-- defaultValue="5" -->
              <a-input-number
                :disabled="addSubjectForm.kmPyzt == 'FORMAL' || addSubjectForm.kmPyzt == 'TEST'"
                v-model:value="addSubjectForm.zjbl"
                :min="0"
                :max="100"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="复评类型" name="fpCountType">
              <a-radio-group
                :disabled="addSubjectForm.kmPyzt == 'FORMAL'"
                v-model:value="addSubjectForm.fpCountType"
              >
                <a-radio-button value="RATIO">按比例</a-radio-button>
                <a-radio-button value="COUNT">按份数</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="addSubjectForm.fpCountType == 'RATIO'">
            <a-form-item
              label="复评比率（%）"
              :disabled="addSubjectForm.kmPyzt == 'FORMAL'"
              name="fpbl"
            >
              <a-input-number v-model:value="addSubjectForm.fpbl" :min="0" :max="100" />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="addSubjectForm.fpCountType == 'COUNT'">
            <a-form-item
              label="复评份数"
              :disabled="addSubjectForm.kmPyzt == 'FORMAL'"
              name="fpCount"
            >
              <a-input-number v-model:value="addSubjectForm.fpCount" :min="0" /> 份
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { getTeacherCard } from '/@/api/system-manage/teacher-info'
import { Rule } from 'ant-design-vue/lib/form'
import { saveOrUpdateSubject } from '/@/api/organization/subjectManage'
import { getCollegeList } from '/@/api/organization/collegeManage'
import { debounce } from 'lodash-es'
import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const userInfo = <any>computed(() => userStore.getUserInfo)
const props = defineProps({
  visible: {
    type: Boolean,
  },
  addSubjectForm: {
    type: Object,
    default: () => {},
  },
})

const validateSjzs = async (_rule: Rule, value: string) => {
  const reg = /^[0-9]*$/
  if (value === '') {
    return Promise.reject('科目分数不能为空')
  } else if (!reg.test(value)) {
    return Promise.reject('科目分数只能为数字')
  } else {
    return Promise.resolve()
  }
}

const rules = {
  kmdm: [{ required: true, message: '科目代码不能为空', trigger: 'blur' }],
  kmmc: [{ required: true, message: '科目名称不能为空', trigger: 'blur' }],
  kmzfs: [{ validator: validateSjzs, trigger: 'blur' }],
  xyxxId: [{ required: true, message: '所属学院不能为空', trigger: 'blur' }],
  kmzz: [{ required: true, message: '评阅组长不能为空', trigger: 'blur' }],
  // timeArr: [{ required: true, message: '请选择考试时间', trigger: 'blur' }],
  spsjfs: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value <= 0) {
          return Promise.reject('试评试卷份数需要大于0')
        } else {
          return Promise.resolve()
        }
      },
      trigger: 'change',
    },
    { required: true, message: '试评试卷份数不能为空', trigger: 'blur' },
  ],
  // ydsjFs: [
  //   {
  //     required: true,
  //     validator: (rule, value, callback) => {
  //       if (value <= 0) {
  //         return Promise.reject('应到份数需要大于0');
  //       } else {
  //         return Promise.resolve();
  //       }
  //     },
  //     trigger: 'change',
  //   },
  //   { required: true, message: '应到份数不能为空', trigger: 'blur' },
  // ],
  zjbl: [
    { required: true, message: '质检比率不能为空', trigger: 'blur' },
    // {
    //   required: true,
    //   validator: (rule, value, callback) => {
    //     if (value <= 0) {
    //       return Promise.reject('质检比率需要大于0');
    //     } else {
    //       return Promise.resolve();
    //     }
    //   },
    //   trigger: 'change',
    // },
  ],
  fpbl: [{ required: true, message: '复评比率不能为空', trigger: 'blur' }],
  fpCount: [
    // {
    //   required: true,
    //   validator: (rule, value, callback) => {
    //     if (value <= 0) {
    //       return Promise.reject('复评份数需要大于0');
    //     } else {
    //       return Promise.resolve();
    //     }
    //   },
    //   trigger: 'change',
    // },
    { required: true, message: '复评份数不能为空', trigger: 'blur' },
  ],
  fpCountType: [{ required: true, message: '复评类型不能为空', trigger: 'blur' }],
}

const emits = defineEmits(['cancel', 'refresh'])
const title = computed(() => (props.addSubjectForm.id ? '编辑科目' : '新增科目'))

const formRef = ref()
const handleClose = async () => {
  emits('cancel')
  await formRef.value.resetFields()
}
const handleOk = async () => {
  try {
    await formRef.value.validate()
    const postData = JSON.parse(JSON.stringify(props.addSubjectForm))
    postData.kmYear = userInfo.value.kmYear
    // postData.beginTime = dayjs(postData.timeArr[0]).format('YYYY-MM-DD HH:mm:ss');
    // postData.endTime = dayjs(postData.timeArr[1]).format('YYYY-MM-DD HH:mm:ss');
    saveOrUpdateSubject(postData).then(res => {
      if (res.code == 200) {
        message.success(`${title.value}成功`)
        emits('refresh')
        handleClose()
      } else {
        message.error(res.message)
      }
    })
  } catch (error) {
    console.log(error)
  }
}

// 获取教师列表
const teacherOptions = ref([])
const getTeacherOptions = async str => {
  const { data } = await getTeacherCard({
    pageSize: 0,
    jsxmOrJsgs: str,
    accountManageFlag: false,
    jsYear: userInfo.value.kmYear,
  })
  data?.forEach(element => {
    element.jsxm = `(${element.jsgs})${element.jsxm}`
  })
  teacherOptions.value = data
}

// 分配教师 教师下拉框筛选
const handleChange = debounce(getTeacherOptions, 500)

// 学院列表
const collegeList = ref([])
const getCollegeOption = async () => {
  try {
    const { data } = await getCollegeList({
      pageNum: 0,
      pageSize: 9999,
    })
    data.forEach(ele => {
      ele.codeName = `${ele.xydm}(${ele.xymc})`
    })
    collegeList.value = data.sort((a, b) => a.xydm - b.xydm)
  } catch (error) {
    console.log(error)
  }
}

// 筛选学院列表选项
const selectFilterOption = (input: string, option: any) => {
  return option.codeName.includes(input)
}

onMounted(() => {
  getCollegeOption()
  if (userInfo.value.accountType == 'XY') {
    props.addSubjectForm.xyxxId = userInfo.value.xyxxId || userInfo.value.xyid
  }
  if (props.addSubjectForm.id) {
    teacherOptions.value = props.addSubjectForm.teacherOptions
    // if (props.addSubjectForm?.beginTime && props.addSubjectForm.beginTime != 'null')
    //   props.addSubjectForm.timeArr = [
    //     dayjs(props.addSubjectForm?.beginTime),
    //     dayjs(props.addSubjectForm?.endTime),
    //   ];
  }
})
</script>
<style lang="less" scoped>
.form {
  width: 100%;
  padding: 16px;
}
</style>
